﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using server.DataBase;
using server.Communication.Messages;

namespace server
{

    class ClientHandler
    {
        private TcpClient client_socket;
        private IFormatter formatter;
        private NetworkStream stream;
        private ServerMessageHandler msgHandler;

        public ClientHandler()
        {
        }

        public void startClient(TcpClient client_socket, Data data)
        {
            this.client_socket = client_socket;
            this.formatter = new BinaryFormatter();
            this.stream = client_socket.GetStream();
            this.msgHandler = new ServerMessageHandler(client_socket, data);
            Thread cThread = new Thread(runClient);
            cThread.Start();
        }

        private void runClient()
        {
            try
            {
                Message msg = new ClientAccepted();
                formatter.Serialize(stream, msg);

                while (true)
                {
                    stream = client_socket.GetStream();
                    msg = (Message)formatter.Deserialize(stream);
                    this.msgHandler.proccessMsg(msg, stream);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                stream.Close();
                client_socket.Close();
            }
        }
    }
}
